<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="代理商">
        <el-select style="padding-bottom: 15px;"
                   filterable
                   clearable
                   v-model="dataForm.agentId" placeholder="请选择">
          <el-option
            :key="0"
            label="厂家"
            :value="0">
          </el-option>
          <el-option
            v-for="item in agentData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="sim卡号">
        <el-input v-model="dataForm.simCode" placeholder="sim卡号" clearable></el-input>
      </el-form-item>
      <el-form-item label="sim手机号">
        <el-input v-model="dataForm.simMobile" placeholder="sim手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备id">
        <el-input v-model="dataForm.deviceId" placeholder="设备id" clearable></el-input>
      </el-form-item>
      <el-form-item label="即将过期">
        <el-select v-model="overdueOption" placeholder="请选择">
          <el-option
            :key="0"
            label="全部"
            :value="0">
          </el-option>
          <el-option
            :key="7"
            label="7天内过期"
            :value="7">
          </el-option>
          <el-option
            :key="15"
            label="15天内过期"
            :value="15">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="expire">已经过期</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button v-if="isAuth('zjwl:simcard:import')" type="primary" @click="uploadHandle()">导入文件</el-button>

        <el-button v-if="isAuth('zjwl:simcard:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('zjwl:simcard:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
        <el-button v-if="isAuth('zjwl:simcard:delete')" type="danger" @click="chooseExpireDate"
                   :disabled="dataListSelections.length <= 0">批量修改到期日期
        </el-button>
        <el-button v-if="isAuth('zjwl:simcard:save')" @click="exportExcel">导出表格</el-button>
      </el-form-item>
    </el-form>
    <el-table
      id="simcardTable"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="simCode"
        header-align="center"
        align="center"
        label="sim卡号">
      </el-table-column>
      <el-table-column
        prop="mobile"
        header-align="center"
        align="center"
        label="sim卡手机号">
      </el-table-column>
      <el-table-column
        prop="activedate"
        header-align="center"
        align="center"
        label="激活时间">
        <template slot-scope="scope">
          {{ scope.row.activedate.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="expireDate"
        header-align="center"
        align="center"
        label="到期时间">
        <template slot-scope="scope">
          {{ scope.row.expireDate.substring(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="deviceId"
        header-align="center"
        align="center"
        label="设备id">
      </el-table-column>
      <el-table-column
        prop="agentUserId"
        header-align="center"
        align="center"
        label="代理商">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.agentId==0">厂家</el-tag>
          <el-tag v-else>{{ scope.row.agentName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        v-if="isAuth('zjwl:simcard:delete')"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100,500,1000]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <upload v-if="uploadVisible" ref="upload" @refreshDataList="refreshAfterExcelDataList"></upload>

    <el-dialog :visible.sync="expireDateVisible"
               title="修改到期时间"
               :append-to-body="true"
               center
               width="50%"
    >
      <el-date-picker
        v-model="expireDate"
        type="date"
        style="margin-left: 30%"
        placeholder="选择日期">
      </el-date-picker>

      <div slot="footer" class="dialog-footer">
        <el-button @click="expireDateVisible = false">关闭</el-button>
        <el-button @click="resetExpireDate" type="primary">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './simcard-add-or-update'
import Upload from './excel-upload'

export default {
  data () {
    return {
      dataForm: {
        agentUserId: '',
        simCode: '',
        simMobile: '',
        deviceId: '',
        agentId: ''
      },
      agentUserData: [],
      agentData: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      uploadVisible: false,
      overdueOption: 0,
      expire: false,
      overdueData: [],
      expireDateVisible: false,
      expireDate: ''
    }
  },
  components: {
    AddOrUpdate,
    Upload
  },
  activated () {
    this.getDataList()
    // this.loadAgentUser()
    this.loadAgent()
    this.getOverdueInfo()
  },
  methods: {
    resetExpireDate () {
      var ids = this.dataListSelections.map(item => {
        return item.id
      })
      this.$http({
        url: this.$http.adornUrl(`/simcard/updateBatch`),
        method: 'post',
        data: this.$http.adornData({
          'simcardIds': ids,
          'expireDate': this.expireDate.getTime()
        }, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.expireDateVisible = false
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    chooseExpireDate () {
      this.expireDateVisible = true
    },
    exportExcel () {
      var xlsxParam = {raw: true}
      let tables = document.getElementById('simcardTable').cloneNode(true)
      tables.removeChild(tables.querySelector('.el-table__fixed-right'))
      // tables.removeChild(tables.querySelector('.el-table__fixed'))
      let tableBook = this.$XLSX.utils.table_to_book(tables, xlsxParam)
      var tableWrite = this.$XLSX.write(tableBook, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        this.$FileSaver.saveAs(
          new Blob([tableWrite], {type: 'application/octet-stream'}),
          'simcard.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, tableWrite)
      }
      return tableWrite
    },
    getOverdueInfo () {
      this.$http({
        url: this.$http.adornUrl('/simcard/overdue'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.overdueData = data.data
        } else {
          this.overdueData = {'over': [], 'seven': [], 'thirty': []}
        }
      })
    },
    // 上传文件
    uploadHandle () {
      this.uploadVisible = true
      this.$nextTick(() => {
        this.$refs.upload.init()
      })
    },
    loadAgent () {
      this.$http({
        url: this.$http.adornUrl('/deviceagent/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 100
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.agentData = data.page.list
        } else {
          this.agentData = []
        }
      })
    },
    loadAgentUser () {
      this.$http({
        url: this.$http.adornUrl('/sys/user/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 100,
          'roleName': '代理商'
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.agentUserData = data.page.list
        } else {
          this.agentUserData = []
        }
      })
    },
    refreshAfterExcelDataList () {
      this.uploadVisible = false
      this.getDataList()
    },
    // 获取数据列表
    getDataList () {
      // if (this.expire === true) {
      //   if (this.overdueData.over.length > 0) {
      //     // this.pageSize = this.overdueData.over.length
      //     this.dataList = this.overdueData.over
      //     this.totalPage = this.overdueData.over.length
      //   }
      //   return
      // }
      // if (this.overdueOption > 0) {
      //   if (this.overdueOption === 7 && this.overdueData.seven.length > 0) {
      //     // this.pageSize = this.overdueData.seven.length
      //     this.dataList = this.overdueData.seven
      //     this.totalPage = this.overdueData.seven.length
      //   }
      //   if (this.overdueOption === 15 && this.overdueData.thirty.length > 0) {
      //     // this.pageSize = this.overdueData.thirty.length
      //     this.dataList = this.overdueData.thirty
      //     this.totalPage = this.overdueData.thirty.length
      //   }
      //   return
      // }
      // this.pageSize = 10
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/simcard/list'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
          // 'agentUserId': this.dataForm.agentUserId,
          'agentId': this.dataForm.agentId,
          'deviceId': this.dataForm.deviceId,
          'simCode': this.dataForm.simCode,
          'simMobile': this.dataForm.simMobile,
          'overdue': this.overdueOption,
          'expire': this.expire
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/simcard/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
